<template>
  <view class="search-page">
    <view class="search-wrap">
      <uni-search-bar
        @confirm="onConfirm"
        @cancel="onCancel"
        @clear="onCancel"
        :focus="true"
        placeholder="搜索关键词"
        v-model="params.keyword">
      </uni-search-bar>
    </view>

    <view class="search-words" v-if="!resultList.length">
      <view class="history" v-if="historyList.length">
        <view class="header">
          <view class="title">最近搜索</view>
          <view class="icon">
            <uni-icons
              type="list"
              size="22"
              @click="removeWords('history')"></uni-icons>
            <uni-icons type="trash" size="24" @click="clearHistory"></uni-icons>
          </view>
        </view>
        <view class="body">
          <view class="words-list">
            <view
              class="item"
              v-for="(words, index) in historyList"
              :key="words">
              <text class="words" @click="clickWords(words)">{{ words }}</text>
              <uni-icons
                v-if="historyCloseState"
                type="clear"
                size="20"
                class="close-icon"
                @click="closeWords('history', index)"></uni-icons>
            </view>
          </view>
        </view>
      </view>
      <view class="recommend" v-if="recommendList.length">
        <view class="header">
          <view class="title">热门搜索</view>
          <view class="icon">
            <uni-icons
              type="list"
              size="22"
              @click="removeWords('recommend')"></uni-icons>
            <uni-icons
              type="trash"
              size="24"
              @click="clearRecommend"></uni-icons>
          </view>
        </view>
        <view class="body">
          <view class="words-list">
            <view
              class="item"
              v-for="(words, index) in recommendList"
              :key="words">
              <text class="words" @click="clickWords(words)">{{ words }}</text>
              <uni-icons
                v-if="recommendCloseState"
                type="clear"
                size="20"
                class="close-icon"
                @click="closeWords('recommend', index)"></uni-icons>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="search-empty" v-if="!resultList.length">
      <uv-empty
        mode="search"
        icon="http://cdn.uviewui.com/uview/empty/search.png"></uv-empty>
    </view>

    <view class="result-wrap" v-if="resultList.length">
      <view class="result-list">
        <navigator
          class="item"
          :url="`/pages/preview/preview?id=${d._id}`"
          v-for="d in resultList"
          :key="d._id"
          @click="preview">
          <image class="image" :src="d.smallPicurl" mode="aspectFill" />
        </navigator>
      </view>
      <view class="loading" v-if="noData || resultList.length">
        <uni-load-more :status="noData ? 'noMore' : 'loading'"></uni-load-more>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, watch } from 'vue'
import { apiSearchHistory } from '@/api'
import { onLoad, onUnload, onReachBottom } from '@dcloudio/uni-app'

const params = ref({
  pageNum: 1,
  pageSize: 12,
  keyword: '',
})
const historyKey = 'b-historyList'
const recommendKey = 'b-recommendList'
const historyList = ref([])
const recommendList = ref(['美女', '宠物', '风景'])
const resultList = ref([])
const noData = ref(false)

watch(
  () => params.value.keyword,
  (val, old) => !val && onCancel(),
)

onLoad(() => {
  const historyData = uni.getStorageSync(historyKey)
  if (historyData) historyList.value = historyData

  const recommendData = uni.getStorageSync(recommendKey)
  if (recommendData) recommendList.value = recommendData
})

const onConfirm = () => {
  if (!historyList.value.includes(params.value.keyword)) {
    historyList.value.unshift(params.value.keyword)
  }
  uni.setStorageSync(historyKey, historyList.value)
  uni.showLoading({
    title: '加载中...',
    mask: true,
  })
  init(params.value.keyword)
  sendSearch()
}

const clickWords = value => {
  if (params.value.keyword === value) return
  else {
    params.value.keyword = value
    uni.showLoading({
      title: '加载中...',
      mask: true,
    })
  }
  onConfirm()
}

// 触底加载更多数据
onReachBottom(() => {
  if (noData.value) return
  params.value.pageNum++
  sendSearch()
})

const sendSearch = async () => {
  try {
    const data = await apiSearchHistory(params.value)

    console.log('%c Line:103 🌭 res', 'color:#7f2b82', data)
    if (params.value.pageSize > data.length) {
      noData.value = true
    }
    if (data.length === 0) return
    resultList.value = [...resultList.value, ...data]
  } finally {
    uni.hideLoading()
  }
}

const onCancel = () => init()
const init = keyword => {
  resultList.value = []
  noData.value = false
  params.value = { pageNum: 1, pageSize: 12, keyword: keyword || '' }
}

const historyCloseState = ref(false)
const recommendCloseState = ref(false)
const removeWords = type => {
  if (type === 'history') {
    historyCloseState.value = !historyCloseState.value
  }
  if (type === 'recommend') {
    recommendCloseState.value = !recommendCloseState.value
  }
}

const closeWords = (type, index) => {
  console.log('%c Line:151 🥝 data, index', 'color:#ffdd4d', type, index)
  if (type === 'history') {
    historyList.value.splice(index, 1)
    uni.setStorageSync(historyKey, historyList.value)
  } else {
    recommendList.value.splice(index, 1)
    uni.setStorageSync(recommendKey, recommendList.value)
  }
}

const clearHistory = () => {
  uni.showModal({
    title: '系统提示',
    content: '是否清除历史搜索？',
    success: ({ confirm, cancel }) => {
      if (confirm) {
        historyList.value = []
        uni.removeStorageSync(historyKey)
      }
    },
  })
}

const clearRecommend = () => {
  uni.showModal({
    title: '系统提示',
    content: '是否清除热门搜索历史？',
    success: ({ confirm, cancel }) => {
      if (confirm) {
        recommendList.value = []
        uni.removeStorageSync(recommendKey)
      }
    },
  })
}

const preview = () => {
  uni.setStorageSync('b-classlist', resultList.value)
}

onUnload(() => {
  // uni.removeStorageSync(historyKey)
  uni.removeStorageSync(recommendKey)
  uni.removeStorageSync('b-classlist')
})
</script>

<style lang="scss" scoped>
.search-words {
  .header {
    padding: 0 30rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: $font-color-3;
    :deep() {
      .uni-icons {
        color: $font-color-3 !important;
      }
    }
    .icon {
      display: flex;
      gap: 10rpx;
      :deep() {
        .uni-icons {
          cursor: pointer;
        }
      }
    }
  }
  .body {
    .words-list {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      gap: 16rpx;
      padding: 30rpx 30rpx;
    }
    .item {
      background-color: $font-color-4;
      border-radius: 5rpx;
      position: relative;
      padding: 16rpx 0;
      .words {
        padding: 0 32rpx;
        font-size: $font-size;
        color: $white-color;
      }
      .close-icon {
        position: absolute;
        top: -20rpx;
        right: -20rpx;
        z-index: 9;
        padding: 10rpx;
        color: $font-color-2 !important;
      }
    }
  }
}

.result-wrap {
  width: 100%;
  padding: 0 20rpx;
  .result-list {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10rpx;
    .item {
      height: 400rpx;
      border-radius: 10rpx;
      overflow: hidden;
      .image {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>
